//
//  BIZCunsultorListViewController.m
//  biz
//
//  Created by zhangfuwei on 2017/4/11.
//  Copyright © 2017年 jieshuibao. All rights reserved.
//

#import "BIZConsultorListViewController.h"

#import "BIZConsultEditViewController.h"
#import "BIZConsultHistoryViewController.h"
#import "BIZConsultDetailTableViewController.h"
#import "BIZConsultorPersonalDetailVC.h"
// cell
#import "BIZConsultorCellNew.h"
#import "BIZConsultorOfflineCell.h"
#import "BIZAdeptSkillCollectionViewcell.h"
#import "BIZNoConsultorCell.h"

// model
#import "BIZConsultorModel.h"
#import "BIZAdeptSkilledModel.h"
#import "BIZAdeptSkillChildrenModel.h"
#import "BIZConsultorListModel.h"
#import "BIZConsultorListDataModel.h"

// view
#import "BIZDefaultSortView.h"
#import "BIZSkillHeaderView.h"

static CGFloat kSearchViewH = 46;
static CGFloat kSortButtonsH = 45;
static CGFloat kTagItemH = 30;
static CGFloat kTagItemW = 100;
static CGFloat kTagMargin = 19;
static CGFloat kCollectionViewH = 300;
static NSString *const kConsultorCellReuseID = @"kConsultorCellReuseID";
/*线下咨询列表cell 重用ID*/
static NSString *const kConsultorOfflineCellReuseID = @"kConsultorOfflineCellReuseID";
static NSString *const kNoSuitableConsultorCellID = @"kNoSuitableConsultorCellID";

static NSString *const kHeaderViewReuseID = @"kHeaderViewReuseID";
static NSString* const kcollectionViewCellReuseID = @"kcollectionViewCellReuseID";

typedef enum : NSUInteger {
    
    BIZConsultorListVCFilterTypeDefault,
    BIZConsultorListVCFilterTypeNewest,
    BIZConsultorListVCFilterTypeLabel
    
} BIZConsultorListVCFilterType;

@interface BIZConsultorListViewController ()<UICollectionViewDelegate,UICollectionViewDataSource,UITableViewDelegate,UITableViewDataSource>

@property (nonatomic, strong) UIButton *rightBtn;
@property (nonatomic, assign) int last;
/** type */
@property (nonatomic, assign) BIZConsultorListViewControllerFromType type;


/** tableView */
@property (nonatomic, strong) UITableView *tableView;

/** 搜索栏 */
@property (nonatomic, strong) UITextField *searchField;

/** 搜索按钮 */
@property (nonatomic, strong) UIButton *searchButton;

/**
 *  默认排序按钮
 */
@property (nonatomic, strong) UIButton *defaultSortBtn;
/**
 *  擅长业务
 */
@property (nonatomic, strong) UIButton *customizedSortBtn;
/** 是否选择默认排序 */
@property (nonatomic, assign) BOOL isDefaultSortType;
/** 默认排序 */
@property (nonatomic, strong) BIZDefaultSortView *sortView;
/** 擅长业务 */
@property (nonatomic, strong) UICollectionView *collectionView;
/** reset */
@property (nonatomic, strong) UIButton *resetBtn;
/** confirm */
@property (nonatomic, strong) UIButton *confirmBtn;

/** skillsModel */
@property (nonatomic, strong) BIZAdeptSkilledModel *skillsModel;
/**  咨询师列表model */
@property (nonatomic, strong) BIZConsultorListModel *listModel;

/** coverView */
@property (nonatomic, strong) UIView *coverView;

/** note */
@property (nonatomic, copy) NSString *taxes;
/** note */
@property (nonatomic, copy) NSString *trade;
/** note */
@property (nonatomic, copy) NSString *topic;

/** topic选中的item */
@property (nonatomic, assign) NSIndexPath *topicSelecedIdxPath;
/** toptaxesic选中的item */
@property (nonatomic, assign) NSIndexPath *taxesSelecedIdxPath;
/** trade选中的item */
@property (nonatomic, assign) NSIndexPath *tradeSelecedIdxPath;


/** 是否为默认的 类型 (网络请求参数type)*/
@property (nonatomic, assign) BOOL isDefaultType;

/** 筛选器类型(label , new ,defautl) */
@property (nonatomic, assign) BIZConsultorListVCFilterType filterType;

/** 当前是否为 搜索状态 */
@property (nonatomic, assign) BOOL isSearchType;

@end

@implementation BIZConsultorListViewController

- (instancetype)initWithType:(BIZConsultorListViewControllerFromType)type
{
    self = [super init];
    if (self) {
        _type = type;
    }
    return self;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    [self setupConfig];
    //  添加排序按钮
    [self addHeaderSortButtons];
    
    [self requestConsultorAdeptSkillList];

}

- (void)setupConfig {
    _filterType = BIZConsultorListVCFilterTypeDefault;
    self.title = @"咨询师";
    _isSearchType = NO;
    _isDefaultSortType = YES;
    _last = 1;
    
    self.view.backgroundColor = HEXCOLOR(0xf9f9f9);
}

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    [self showO2ORedView];
    [self.tableView.mj_header beginRefreshing];
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc]initWithCustomView:self.rightBtn];
}

- (void)addHeaderSortButtons {

    [self.view addSubview:self.searchField];
    [self.view addSubview:self.searchButton];
    
    [self.view addSubview:self.defaultSortBtn];
    [self.view addSubview:self.customizedSortBtn];

    [self.searchButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(self.searchField.mas_right).offset(17);
        make.top.equalTo(self.view).offset(15);
    }];
}

- (void)showO2ORedView
{
    if (![BIZUserModel shareUser].login) {
        return;
    }
    
    [RequestTool POST:kO2OConsultRedUrl parameters:nil progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        DeLog(@"responseObject %@", responseObject);
        
        if ([responseObject[@"code"] integerValue] == 1) {
            if ([responseObject[@"data"] integerValue] == 1) {
                [self.rightBtn showBadge];
            }
            else {
                 [self.rightBtn hidenBadge];
            }
        }
        else {
            [MBProgressHUD showInfoMessage:responseObject[@"des"]];
        }
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        DeLog(@"error %@", error);
        if ([AFNetworkReachabilityManager sharedManager].networkReachabilityStatus == AFNetworkReachabilityStatusNotReachable) {
            [MBProgressHUD showErrorMessage:@"网络不给力"];
        }
        else {
            [MBProgressHUD showErrorMessage:@"服务器繁忙"];
        }
    }];
}

- (void)searchItemDidClicked:(UIBarButtonItem *)barButtonItem {
    
}

- (void)historyItemDidClicked:(UIBarButtonItem *)barButtonItem {
    BIZConsultHistoryViewController *history = [[BIZConsultHistoryViewController alloc] init];
    [self.navigationController pushViewController:history animated:YES];
}


- (void)stopRefresh
{
    !self.tableView.mj_header.isRefreshing ? : self.tableView.mj_header.endRefreshing;
    !self.tableView.mj_footer.isRefreshing ? : self.tableView.mj_footer.endRefreshing;
}

#pragma mark --  咨询师列表
- (void)requestConsultorWithType:(NSString *)type taxes:(NSString *)taxes trade:(NSString *)trade topic:(NSString *)topic
{
    DeLog(@"%@,%@ %@ %@",type,trade,taxes,topic);
    if ( [type isEqualToString:@"default"] ||!type || ([type isEqualToString:@"label"] && !taxes && !trade && !topic)) {
        _isDefaultType = YES;
    }else {
        _isDefaultType = NO;
    }
    [_defaultSortBtn setTitle:_isDefaultType?@"默认排序":@"最新" forState:UIControlStateNormal];

    NSDictionary *param = @{@"pageIndex" : @(_last), @"pageEnd" : @(_last + 9),@"type":type?:@"default",@"taxes":taxes?:@"",@"trade":trade?:@"",@"topic":topic?:@""};
    
    NSString *URLStr = _type == BIZConsultorListViewControllerTypeFromHome ?kConsultorListUrl:kOfflineConsultorsListURL;
    
    [RequestTool POST:URLStr
           parameters:param
             progress:nil
              success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
                  
                  DeLog(@"咨询师列表response %@", responseObject);
                  [self stopRefresh];
                  int code = [responseObject[@"code"] intValue];
                  if (code == 1) {
                      BIZConsultorListModel *model = [BIZConsultorListModel yy_modelWithJSON:responseObject];
                      if (_last == 1) {
                          self.listModel = model;
                      }else{
                          
                          self.listModel.data = [self.listModel.data arrayByAddingObjectsFromArray:model.data];
                      }
                      _last += (int)model.data.count;
                      [self.tableView reloadData];
                    
                  } else if (code == 2) {
                      [MBProgressHUD showTipMessageInView:@"请登录"];
                      [BIZUserModel shareUser].login = NO;
                      [self presentViewController:[BIZLoginViewController viewControllerFromStoryboard] animated:YES completion:nil];
                  } else {
                      [MBProgressHUD showErrorMessage:responseObject[@"des"]];
                  }
                  
              }
              failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
//                  [MBProgressHUD showErrorMessage:@"网络不给力,请检测网络" timer:2.5];
                  if ([AFNetworkReachabilityManager sharedManager].networkReachabilityStatus == AFNetworkReachabilityStatusNotReachable) {
                      [MBProgressHUD showErrorMessage:@"网络不给力"];
                  }
                  else {
                      [MBProgressHUD showErrorMessage:@"服务器繁忙"];
                  }
                  
                  [self stopRefresh];
                  if (self.collectionView) {
                      [self removeCoverViewAndSubViews];
                      [self resetSelectedIdxPathAndMarks];
                  }

              }
     ];
}


#pragma mark -- 擅长业务标签列表
- (void)requestConsultorAdeptSkillList {
    
    [RequestTool POST:kConsultorAdeptSkill
           parameters:nil
             progress:nil
              success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
                  DeLog(@"擅长业务标签列表--%@",responseObject);
                  [MBProgressHUD showSuccessMessage:@"业务标签请求成功"];
                  BIZAdeptSkilledModel *skillsModel = [BIZAdeptSkilledModel yy_modelWithJSON:responseObject];
                  if (skillsModel.code.intValue == 1) {
                      
                      self.skillsModel = skillsModel;
                      [self.collectionView reloadData];
                      
                  }else if (skillsModel.code.intValue == 2){
                      [MBProgressHUD showTipMessageInView:@"请登录"];
                      [BIZUserModel shareUser].login = NO;
                      [self presentViewController:[BIZLoginViewController viewControllerFromStoryboard] animated:YES completion:nil];

                  }else{
                      
                      [MBProgressHUD showErrorMessage:skillsModel.des];
                  }

              }
              failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
//                  [MBProgressHUD showErrorMessage:@"网络不给力,请检测网络" timer:2.5];
                  DeLog(@"error ---%@",error);
                  if ([AFNetworkReachabilityManager sharedManager].networkReachabilityStatus == AFNetworkReachabilityStatusNotReachable) {
                      [MBProgressHUD showErrorMessage:@"网络不给力"];
                  }
                  else {
                      [MBProgressHUD showErrorMessage:@"服务器繁忙"];
                  }
              }
     ];
    
}

#pragma mark -- 搜索咨询师

- (void)requestConsultorWithSearchString:(NSString *) searchStr
{
    [MBProgressHUD showActivityMessageInView:nil];
    NSDictionary *param = @{@"pageIndex" : @(_last), @"pageEnd" : @(_last + 9),@"name":searchStr};
    
    [RequestTool POST:kConsultorSearchUrl
           parameters:param
             progress:nil
              success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
                  
                  DeLog(@"咨询师列表response %@", responseObject);
                  [MBProgressHUD hideHUD];
                  [self stopRefresh];
                  int code = [responseObject[@"code"] intValue];
                  if (code == 1) {
                      BIZConsultorListModel *model = [BIZConsultorListModel yy_modelWithJSON:responseObject];
                      if (_last == 1) {
                          self.listModel = model;
                      }else{
                          
                          self.listModel.data = [self.listModel.data arrayByAddingObjectsFromArray:model.data];
                      }
                      _last += (int)model.data.count;
                      [self.tableView reloadData];
                      
                  } else if (code == 2) {
                      [MBProgressHUD showTipMessageInView:@"请登录"];
                      [BIZUserModel shareUser].login = NO;
                      [self presentViewController:[BIZLoginViewController viewControllerFromStoryboard] animated:YES completion:nil];
                  } else {
                      [MBProgressHUD showErrorMessage:responseObject[@"des"]];
                  }
                  
              }
              failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
                  //                  [MBProgressHUD showErrorMessage:@"网络不给力,请检测网络" timer:2.5];
                  if ([AFNetworkReachabilityManager sharedManager].networkReachabilityStatus == AFNetworkReachabilityStatusNotReachable) {
                      [MBProgressHUD showErrorMessage:@"网络不给力"];
                  }
                  else {
                      [MBProgressHUD showErrorMessage:@"服务器繁忙"];
                  }
                  
                  [self stopRefresh];
                  if (self.collectionView) {
                      [self removeCoverViewAndSubViews];
                      [self resetSelectedIdxPathAndMarks];
                  }
                  
              }
     ];
}


#pragma mark - Table view data source

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    if (self.listModel.data.count) {
        
        return self.listModel.data.count;
    }else{
        return 1;
    }
}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    if (self.listModel.data.count) {
        switch (_type) {
            case BIZConsultorListViewControllerTypeFromHome:{
                
                BIZConsultorCellNew *cell = [tableView dequeueReusableCellWithIdentifier:kConsultorCellReuseID forIndexPath:indexPath];
                cell.dataModel = self.listModel.data[indexPath.row];
                
                return cell;
   
            }
                break;
            case BIZConsultorListViewControllerTypeFromOffline:{
                
                BIZConsultorOfflineCell *cell = [tableView dequeueReusableCellWithIdentifier:kConsultorOfflineCellReuseID forIndexPath:indexPath];
                cell.dataModel = self.listModel.data[indexPath.row];
                
                return cell;
   
            }
                break;
            
                
            case BIZConsultorListViewControllerTypeFromContract:{
                
                BIZConsultorCellNew *cell = [tableView dequeueReusableCellWithIdentifier:kConsultorCellReuseID forIndexPath:indexPath];
                cell.dataModel = self.listModel.data[indexPath.row];
                
                return cell;
                
            }
                break;
                
            default:
                break;
        }
//        BIZConsultorCellNew *cell = [tableView dequeueReusableCellWithIdentifier:CellID forIndexPath:indexPath];
//        cell.dataModel = self.listModel.data[indexPath.row];
//        
//        return cell;
    }else{
        BIZNoConsultorCell *cell = [tableView dequeueReusableCellWithIdentifier:kNoSuitableConsultorCellID forIndexPath:indexPath];
        return cell;

    }
}


#pragma mark - Table view delegate

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (!self.listModel.data.count) {
        return;
    }
    [MBProgressHUD showInfoMessage:@"进入咨询师个人主页" timer:1.0];
    BIZConsultorListDataModel *dataM = self.listModel.data[indexPath.row];
    
    
    BIZConsultorPersonalDetailVC *detailVC = [[BIZConsultorPersonalDetailVC alloc] initWithTypeFrom:(BIZConsultorPersonalDetailVCTypeFrom)_type];

    detailVC.dataM = dataM;

    [self.navigationController pushViewController:detailVC animated:YES];
}

#pragma mark -- uicollectionView的数据源,代理
-(NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView {
    return self.skillsModel.data.count;
}

-(NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    
    BIZAdeptSkillChildrenModel *childrenM = self.skillsModel.data[section];
    return childrenM.children.count;
}

-(UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    BIZAdeptSkillCollectionViewcell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:kcollectionViewCellReuseID forIndexPath:indexPath];
    
    BIZAdeptSkillChildrenModel *childrenM = self.skillsModel.data[indexPath.section];
    BIZAdeptSkillChildrenModel *subChildrenM = childrenM.children[indexPath.row];
    
    cell.content = subChildrenM.name;

    return cell;
}
////这个方法是返回 Header的大小 size
//-(CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout referenceSizeForHeaderInSection:(NSInteger)section{
//    return CGSizeMake(Main_Screen_Width, 50);
//}

//这个也是最重要的方法 获取Header的 方法。
- (UICollectionReusableView *)collectionView:(UICollectionView *)collectionView viewForSupplementaryElementOfKind:(NSString *)kind atIndexPath:(NSIndexPath *)indexPath
{
    BIZAdeptSkillChildrenModel *childrenM = self.skillsModel.data[indexPath.section];
    UILabel *lab = [[UILabel alloc] initWithFrame:CGRectMake(15, 0, 100, 45)];
    lab.text = childrenM.name;
    
    if ([kind isEqualToString:UICollectionElementKindSectionHeader]) {
        
        //从缓存中获取 Headercell
        UICollectionReusableView *header = [collectionView dequeueReusableSupplementaryViewOfKind:kind withReuseIdentifier:kHeaderViewReuseID forIndexPath:indexPath];
        for (UIView *subview in header.subviews) {
            if ([subview isKindOfClass:[UILabel class]]) {
                [subview removeFromSuperview];
            }
        }
        [header addSubview:lab];
        return header;
    }
    return nil;
}

- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath{
    [self resetFilter];

    // id赋值
    BIZAdeptSkillChildrenModel *childrenM = self.skillsModel.data[indexPath.section];
    BIZAdeptSkillChildrenModel *subChildrenM = childrenM.children[indexPath.row];

    switch (subChildrenM.pid.intValue) {
        case 1:// 行业
            _tradeSelecedIdxPath? [collectionView deselectItemAtIndexPath:_tradeSelecedIdxPath animated:YES]:nil;
            _trade = subChildrenM.uuid;
            _tradeSelecedIdxPath =indexPath;

            break;
        case 2:// 税种
            _taxesSelecedIdxPath ? [collectionView deselectItemAtIndexPath:_taxesSelecedIdxPath animated:YES]:nil;

            _taxes = subChildrenM.uuid;
            _taxesSelecedIdxPath = indexPath;
            break;
        case 3:// 专题
            _topicSelecedIdxPath? [collectionView deselectItemAtIndexPath:_topicSelecedIdxPath animated:YES]:nil;
            
            _topic =  subChildrenM.uuid;
            _topicSelecedIdxPath = indexPath;

            break;
     
        default:
            break;
    }

}

- (void)clickSearchButton:(UIButton *)btn {
    [self.searchField resignFirstResponder];
    if ([self.searchField.text isEqualToString:@""]) {
        [MBProgressHUD showTipMessageInView:@"请输入要查询的咨询师"];
        return;
    }
    _last = 1;
    _isSearchType = YES;
    self.listModel = nil;
    [self requestConsultorWithSearchString:self.searchField.text];
}

#pragma mark -- 私有方法

- (void)clickSectionHeaderBtn:(UIButton *)btn {
    
    [self removeCoverViewAndSubViews];
    
    if (btn.tag == 100) { // 默认排序
        
        _defaultSortBtn.selected = YES;
        _customizedSortBtn.selected = NO;

        [self.view insertSubview:self.coverView aboveSubview:self.tableView];
        [self.view insertSubview:self.sortView aboveSubview:self.coverView];
        
    }else {//  擅长业务

        _isDefaultSortType = NO;
        _defaultSortBtn.selected = NO;
        _customizedSortBtn.selected = YES;

        [self.view insertSubview:self.coverView aboveSubview:self.tableView];
        [self.view insertSubview:self.collectionView aboveSubview:self.coverView];
        [self.view insertSubview:self.resetBtn aboveSubview:self.coverView];
        [self.view insertSubview:self.confirmBtn aboveSubview:self.coverView];
        if (!self.skillsModel.data.count) {
            [self requestConsultorAdeptSkillList];
        }
        
    }
    
}

#pragma mark -- 懒加载

-(UITextField *)searchField {
    if (!_searchField) {
        _searchField = [[UITextField alloc] initWithFrame:CGRectMake(48, 8, Main_Screen_Width-(48+84), 30)];
        
        NSAttributedString *attStr = [[NSAttributedString alloc] initWithString:@"请输入咨询师姓名" attributes:@{NSForegroundColorAttributeName:HEXCOLOR(0x909090),NSFontAttributeName:CHINESE_SYSTEM(13)}];
        
        _searchField.attributedPlaceholder = attStr;
        _searchField.layer.borderColor = COLOR_NAVBAR_BLUE.CGColor;
        _searchField.layer.borderWidth = 1.0f;
        _searchField.layer.cornerRadius = 15.0f;
        _searchField.layer.masksToBounds = YES;
        
        _searchField.font = CHINESE_SYSTEM(13);
        _searchField.textColor = [UIColor blackColor];
        _searchField.textAlignment = NSTextAlignmentCenter;
        
    }
    return _searchField;
}

- (UIButton *)searchButton {
    if (!_searchButton) {
        _searchButton = [[UIButton alloc]initWithFrame:CGRectMake(0, 0, 27, 27)];
        [_searchButton setImage:[UIImage imageNamed:@"consultor_search"] forState:UIControlStateNormal];
        [_searchButton addTarget:self action:@selector(clickSearchButton:) forControlEvents:UIControlEventTouchUpInside];
    }
    return _searchButton;
}

- (UIButton *)defaultSortBtn {
    if (!_defaultSortBtn) {
        _defaultSortBtn = [[UIButton alloc] initWithFrame:CGRectMake(0, kSearchViewH, Main_Screen_Width/2, kSortButtonsH)];
        
        _defaultSortBtn.backgroundColor = [UIColor whiteColor];
        
        _defaultSortBtn.tag = 100;
        [_defaultSortBtn setTitle:@"默认排序" forState:UIControlStateNormal];
        [_defaultSortBtn setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
        [_defaultSortBtn setTitleColor:COLOR_NAVBAR_BLUE forState:UIControlStateSelected];
        [_defaultSortBtn addTarget:self action:@selector(clickSectionHeaderBtn:) forControlEvents:UIControlEventTouchUpInside];
        _defaultSortBtn.selected = YES;
    }
    return _defaultSortBtn;
}

- (UIButton *)customizedSortBtn {
    if (!_customizedSortBtn) {
        
        _customizedSortBtn = [[UIButton alloc] initWithFrame:CGRectMake(Main_Screen_Width/2, kSearchViewH, Main_Screen_Width/2, kSortButtonsH)];
        
        _customizedSortBtn.backgroundColor = [UIColor whiteColor];
        
        _customizedSortBtn.tag = 101;
        [_customizedSortBtn setTitle:@"擅长业务" forState:UIControlStateNormal];
        [_customizedSortBtn setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
        [_customizedSortBtn setTitleColor:COLOR_NAVBAR_BLUE forState:UIControlStateSelected];
        [_customizedSortBtn addTarget:self action:@selector(clickSectionHeaderBtn:) forControlEvents:UIControlEventTouchUpInside];
    }
    return _customizedSortBtn;
}
- (UITableView *)tableView {
    if (!_tableView) {
        
        CGRect tableViewFrame = CGRectMake(0, kSearchViewH+kSortButtonsH+5, Main_Screen_Width, self.view.bounds.size.height - kSortButtonsH-BIZNavgationBarH-kSearchViewH-5);
        _tableView = [[UITableView alloc] initWithFrame:tableViewFrame style:UITableViewStylePlain];
        _tableView.backgroundColor = HEXCOLOR(0xf9f9f9);
        _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        _tableView.showsVerticalScrollIndicator = NO;
        _tableView.tableFooterView = [UIView new];
        
        [_tableView registerClass:[BIZConsultorCellNew class] forCellReuseIdentifier:kConsultorCellReuseID];
        [_tableView registerClass:[BIZConsultorOfflineCell class] forCellReuseIdentifier:kConsultorOfflineCellReuseID];
        
        [_tableView registerNib:[UINib nibWithNibName:@"BIZNoConsultorCell" bundle:nil] forCellReuseIdentifier:kNoSuitableConsultorCellID];
        _tableView.estimatedRowHeight = 90;
        _tableView.rowHeight = UITableViewAutomaticDimension;
        _tableView.delegate = self;
        _tableView.dataSource = self;
        
        _tableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
            _last = 1;
            [self refreshData];
        }];
        
        _tableView.mj_footer = [MJRefreshBackNormalFooter footerWithRefreshingBlock:^{
            [self refreshData];
        }];
        
        [self.view addSubview:_tableView];
    }
    return _tableView;
}

- (void)refreshData {
    if (_isSearchType) {
        if (![self.searchField.text isEqualToString:@""]) {
            
            [self requestConsultorWithSearchString:self.searchField.text];
            return;
        }else {
            [self stopRefresh];
            [MBProgressHUD showTipMessageInView:@"请输入搜索咨询师"];
            return;
        }
    }
    NSString *type ;
    switch (_filterType) {
        case BIZConsultorListVCFilterTypeDefault:
            type = @"default";
            break;
        case BIZConsultorListVCFilterTypeNewest:
            type = @"new";
            break;
        case BIZConsultorListVCFilterTypeLabel:
            type = @"label";
            break;
        default:
            break;
    }
    [self requestConsultorWithType:type taxes:_taxes trade:_trade topic:_topic];
    
}

- (UIView *)coverView {
    if (!_coverView) {
        _coverView = [[UIView alloc] initWithFrame:CGRectMake(0, kSortButtonsH, Main_Screen_Width, self.view.bounds.size.height-kSortButtonsH)];
        _coverView.backgroundColor = [UIColor blackColor];
        _coverView.alpha = 0.68;
        UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(removeCoverViewAndSubViews)];
        [_coverView addGestureRecognizer:tap];

    }
    return _coverView;
}

- (BIZDefaultSortView *)sortView {
    if (!_sortView) {
        _sortView = [[BIZDefaultSortView alloc] initWithFrame:CGRectMake(0, kSortButtonsH, Main_Screen_Width, 100)];
        _sortView.block = [self returnSortViewBlock];
        _sortView.isDefaultType = _isDefaultType;

    }
    return _sortView;
}

- (BIZDefaultSortViewClickButtonBlock)returnSortViewBlock {
    BIZDefaultSortViewClickButtonBlock block = nil;
    __weak BIZConsultorListViewController *weakSelf = self;
    
    block = ^(NSInteger tag){
        
        _filterType = tag == 1?BIZConsultorListVCFilterTypeDefault : BIZConsultorListVCFilterTypeNewest;
        _isDefaultSortType = YES;
        //  当前不是搜索类型
        _isSearchType = NO;
        self.listModel = nil;
        _last = 1;
        
        [weakSelf removeCoverViewAndSubViews];
        
        [weakSelf resetFilter];
        
        [weakSelf requestConsultorWithType:_filterType == BIZConsultorListVCFilterTypeDefault ?@"default":@"new" taxes:_taxes trade:_trade topic:_topic];
    };
    
    
    return block;
}

- (void)resetFilter {
    
    // MARK:TO DO 重置筛选器
    _trade = nil;
    _taxes = nil;
    _topic = nil;

}

- (UICollectionView *)collectionView {
    if (!_collectionView) {
        UICollectionViewFlowLayout *layout = [[UICollectionViewFlowLayout alloc] init];
        layout.itemSize = CGSizeMake(kTagItemW,kTagItemH);
        layout.sectionInset = UIEdgeInsetsMake(0, kTagMargin, kTagMargin, kTagMargin);
        layout.minimumLineSpacing = kTagMargin;
        layout.scrollDirection = UICollectionViewScrollDirectionVertical;
        layout.headerReferenceSize=CGSizeMake(self.view.frame.size.width, 50);
        
        _collectionView = [[UICollectionView alloc]initWithFrame:CGRectMake(0, kSortButtonsH, Main_Screen_Width, kCollectionViewH) collectionViewLayout:layout];
        
        [_collectionView registerNib:[UINib nibWithNibName:@"BIZAdeptSkillCollectionViewcell" bundle:nil] forCellWithReuseIdentifier:kcollectionViewCellReuseID];
        [_collectionView registerClass:[UICollectionReusableView class] forSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:kHeaderViewReuseID];
        
        _collectionView.backgroundColor = [UIColor whiteColor];
        _collectionView.scrollEnabled = YES;
        _collectionView.delegate = self;
        _collectionView.dataSource = self;
        _collectionView.allowsMultipleSelection = YES;
        //    collectionView.allowsSelection = YES;

    }
    return _collectionView;
}

- (UIButton *)resetBtn {
    if (!_resetBtn) {
        
        _resetBtn = [[UIButton alloc] initWithFrame:CGRectMake(0, kSortButtonsH+kCollectionViewH,Main_Screen_Width/2, 50)];
        _resetBtn.backgroundColor = [UIColor whiteColor];
        [_resetBtn setTitle:@"重置" forState:UIControlStateNormal];
//        [_resetBtn setTitleColor:COLOR_WORD_GRAY_1 forState:UIControlStateNormal];
        [_resetBtn setTitleColor:COLOR_WORD_GRAY_2 forState:UIControlStateNormal];
        [_resetBtn addTarget:self action:@selector(resetBtnClick:) forControlEvents:UIControlEventTouchUpInside];
        _resetBtn.titleEdgeInsets = UIEdgeInsetsMake(5, 5, 5, 5);
    }
    return _resetBtn;
}

- (UIButton *)confirmBtn {
    if (!_confirmBtn) {
        
        _confirmBtn = [[UIButton alloc] initWithFrame:CGRectMake(Main_Screen_Width/2, kSortButtonsH+kCollectionViewH,Main_Screen_Width/2, 50)];
        _confirmBtn.backgroundColor = [UIColor whiteColor];
        [_confirmBtn setTitle:@"完成" forState:UIControlStateNormal];
        [_confirmBtn setTitleColor:COLOR_WORD_BLUE forState:UIControlStateNormal];
        [_confirmBtn addTarget:self action:@selector(confirmBtnClick:) forControlEvents:UIControlEventTouchUpInside];
        _confirmBtn.titleEdgeInsets = UIEdgeInsetsMake(5, 5, 5, 5);
    }
    return _confirmBtn;
}

- (void)confirmBtnClick:(UIButton *)btn {
    
    _last = 1;
    self.listModel = nil;
    //  当前不是搜索类型
    _isSearchType = NO;

    _filterType = BIZConsultorListVCFilterTypeLabel;
    [self requestConsultorWithType:@"label" taxes:_taxes trade:_trade topic:_topic];
    [self removeCoverViewAndSubViews];
    
}

- (void)resetBtnClick:(UIButton *)btn {
    
    [self resetSelectedIdxPathAndMarks];
    
    [self resetFilter];
}

//  重置所有的标识符和indexPath
- (void)resetSelectedIdxPathAndMarks {
    _topicSelecedIdxPath? [self.collectionView deselectItemAtIndexPath:_topicSelecedIdxPath animated:YES]:nil;
    _taxesSelecedIdxPath? [self.collectionView deselectItemAtIndexPath:_taxesSelecedIdxPath animated:YES]:nil;
    _tradeSelecedIdxPath? [self.collectionView deselectItemAtIndexPath:_tradeSelecedIdxPath animated:YES]:nil;
    
    _topicSelecedIdxPath = nil;
    _taxesSelecedIdxPath = nil;
    _tradeSelecedIdxPath = nil;

}

- (void)removeCoverViewAndSubViews {
    !self.sortView ?: [self.sortView removeFromSuperview];
    !self.collectionView ?: [self.collectionView removeFromSuperview];
    !self.coverView ?: [self.coverView removeFromSuperview];
    !self.resetBtn ?: [self.resetBtn removeFromSuperview];
    !self.confirmBtn ?: [self.confirmBtn removeFromSuperview];
    
    self.sortView = nil;
    self.resetBtn = nil;
    self.confirmBtn = nil;
    self.collectionView = nil;
    self.coverView = nil;
    
    [self resetSelectedIdxPathAndMarks];
}

- (UIButton *)rightBtn
{
    if (!_rightBtn) {
        _rightBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        _rightBtn.frame = CGRectMake(0, 0, 31/2, 37/2);
        [_rightBtn setBackgroundImage:[UIImage imageNamed:@"consult-history"] forState:UIControlStateNormal];
        [_rightBtn addTarget:self action:@selector(historyItemDidClicked:) forControlEvents:UIControlEventTouchUpInside];
    }
    
    return _rightBtn;
}

@end
